#include <stdint.h>
#include <time.h>

/* Here are a series of filters that run without needing a global buffer
 * or complex buffer allocations, they work on the passed buffer
 * directly and return the same pointer they started with */
 
#define pcm_output_frames_to_bytes(X) X*4
//add global handle here maybe

void* sp_filter_default(char* buffer, uint32_t buffer_size){
	//dummy filter
	return buffer;
}

void* sp_filter_silence_left(char* buffer, uint32_t buffer_size){
	//removes the left channel from a pcm buffer
	short* b = (short*) buffer;
	int x;
	for (x = 0; x <= pcm_output_frames_to_bytes(buffer_size); x += 2) {
		b[x] = 0x0000;
	}
	
	return (void*) buffer;
}

void* sp_filter_silence_right(char* buffer, uint32_t buffer_size){
	//removes the right channel from pcm buffer
	short* b = (short*) buffer;
	int x;
	for (x = 0; x < pcm_output_frames_to_bytes(buffer_size); x += 2) {
		b[x+1] = 0;
	}
	return (void*) buffer;
}

void* sp_filter_suppress_output(char* buffer, uint32_t buffer_size){
	//make every sample zero
	int x = pcm_output_frames_to_bytes(buffer_size);
	while(x--) buffer[x] = 0;
	return (void*) buffer;
}

void* sp_filter_ten_millisecond_echo(char* buffer, uint32_t buffer_size){
	//average the previous buffer with this one cumulatively
	static short oldbuf[2304] = {}; //this is evil, but it WILL work with the mp3 decoder
	short* b = (short*) buffer;
	short t;
	int x;
	for(x=2304; x>=0; x--) {
		//t = b[x];
		b[x] = (oldbuf[x] + b[x])/2;
		oldbuf[x] = b[x];
		//oldbuf[x] = t;
	}
	return (void*) buffer;
}

void* sp_filter_ten_millisecond_echo2(char* buffer, uint32_t buffer_size){
	//average the previous buffer with this one
	static short oldbuf[2304] = {}; //this is evil, but it WILL work with the mp3 decoder
	short* b = (short*) buffer;
	short t;
	int x;
	for(x=2304; x>=0; x--) {
		t = b[x];
		b[x] = (oldbuf[x] + b[x])/2;
		oldbuf[x] = t;
	}
	return (void*) buffer;
}

void* sp_filter_sample_noise(char* buffer, uint32_t buffer_size){
	//modify a random number in the sample
	int x = srand(time(NULL));
	int y = pcm_output_frames_to_bytes(buffer_size);
	
	while(--y>0) buffer[x] = (buffer[x]+rand())/2;
	return (void*) buffer;
}
